package com.lykj.llw.box.ui.activity.agent

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SPUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.data.bean.response.AgentLoginResponse
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.databinding.ActAgentMobileLoginBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 代理-手机验证码登录
 * ================================================
 *
 * @author gosha
 * @date 2023/10/31-15:00
 */
class AgentMobileLoginActivity : BaseActivity() {
    lateinit var binding: ActAgentMobileLoginBinding

    private var mCountDownTimer: CountDownTimer? = null
    private var mShareCode = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActAgentMobileLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    override fun initUI() {
        mShareCode = intent?.getStringExtra("code").toString()

        binding.titleBar.tvTitle.text = "登录"
        binding.titleBar.tvRightOption.visibility = View.GONE
    }

    /**
     * 发送验证码
     */
    private fun sendVCode(phone: String) {
        RetrofitManager.instance.senVCode(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@AgentMobileLoginActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                ToastUtils.showShort(this@AgentMobileLoginActivity, "发送验证码")
                binding.tvYzm.alpha = 0.7f
                mCountDownTimer = object : CountDownTimer(60 * 1000, 1000) {
                    override fun onTick(millisUntilFinished: Long) {
                        binding.tvYzm.text = "倒计时${(millisUntilFinished) / 1000}秒"
                    }

                    override fun onFinish() {
                        binding.tvYzm.text = "获取验证码"
                        binding.tvYzm.alpha = 1.0f
                    }
                }.start()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { ToastUtils.showShort(this@AgentMobileLoginActivity, it) }
            }

        }, phone)
    }

    /**
     * 登录
     */
    private fun login() {
        clearBodyParam()
        initBodyParam()
        bodyParams["tel"] = binding.etPhone.text.toString()
        bodyParams["yzm"] = binding.etYzm.text.toString()
        bodyParams["shareCode"] = mShareCode
//        bodyParams["channelId"] = "laiyuekj"

        RetrofitManager.instance.agentLogin(bodyParams, object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@AgentMobileLoginActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean =
                    GsonUtils.fromJson(responseBody, AgentLoginResponse::class.java)

                if (null != bean.data) {
                    BaseApplication.instance?.setAgentUserInfo(bean)

                    val jsonStr = GsonUtils.toJson(bean)
                    //存储用户信息到内存及本地
                    SPUtils.getInstance("agent_user").put("userInfo", jsonStr, true)

                    FlowBus.with<String>(BConstants.BUS_KEY.AGENT_LOGIN_SUCCESS)
                        .post(lifecycleScope, "")
                    ToastUtils.showShort(this@AgentMobileLoginActivity, "登录成功")

                    finish()
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let { ToastUtils.showShort(this@AgentMobileLoginActivity, it) }
            }

        })
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.tvRegister.clickWithTrigger(100) {
            var url = "https://h5-share.66wsy.com/agentShare?code=${mShareCode}";
            try {
                val intent = Intent()
                intent.action = "android.intent.action.VIEW"
                val url = Uri.parse(url)
                intent.data = url
                startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        binding.tvYzm.clickWithTrigger(350) {
            if (binding.tvYzm.text.toString() != "获取验证码") {
                return@clickWithTrigger
            }

            if (binding.etPhone.text.toString().length != 11) {
                ToastUtils.showShort(this, "先输入正确11位手机号")
                return@clickWithTrigger
            }

            sendVCode(binding.etPhone.text.toString())
        }

        binding.tvBtnLogin.clickWithTrigger(500) {
            if (binding.etPhone.text.toString().length != 11) {
                ToastUtils.showShort(this, "请输入正确11位手机号")
                return@clickWithTrigger
            }

            if (binding.etYzm.text.isNullOrBlank()) {
                ToastUtils.showShort(this, "请输入短信验证码")
                return@clickWithTrigger
            }

            login()
        }

        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (it == 0) {
                binding.etPhone.clearFocus()
                binding.etYzm.clearFocus()
            }
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}